package com.westa.smallshop.common;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewStub;

import com.bumptech.glide.Glide;
import com.westa.smallshop.R;
import com.westa.smallshop.data.Base;
import com.westa.smallshop.widget.EndlessRecyclerOnScrollListener;
import com.westa.smallshop.widget.ScrollChildSwipeRefreshLayout;

import butterknife.BindView;

/**
 * Created by Dune on 16/8/8.
 */
public abstract class BaseListFragment<P, O extends Base>
        extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,
        BaseListView<P, O>, LoadDataInterface {


    public static final String INIT_TAG = "init_data";
    private int mPosition = -1;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    @BindView(R.id.refresh_layout)
    ScrollChildSwipeRefreshLayout refreshLayout;

    @BindView(R.id.vs_empty_view)
    ViewStub mVsEmptyView;

    View mEmptyView;

    private EndlessRecyclerOnScrollListener mEndlessRecyclerOnScrollListener;

    private long mLastLoadTime = 0;
    private boolean isInitData = true;

    private BaseListAdapter mAdapter;


    @Override
    public void loadingData(@DelayTime int delayTime) {

        long time = System.currentTimeMillis();
        switch (delayTime) {
            case DELAYED:
            case LOADING:
                if (time - mLastLoadTime > getResources().getInteger(R.integer.refresh_cycle)) {
                    new Handler().postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    setRefreshing(true);
                                }
                            }, delayTime);
                }
                break;
            case IMMEDIATELY:
                setRefreshing(true);
                break;
        }
        mLastLoadTime = time;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isInitData = getArguments().getBoolean(INIT_TAG, true);
        }

    }

    public RecyclerView getRecyclerView() {
        return recyclerView;
    }

    @Override
    public void initView() {

        refreshLayout.setColorSchemeResources(R.color.colorDominant);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setScrollUpChild(recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mEndlessRecyclerOnScrollListener = new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore(int currentPage) {
                loadMoreData(currentPage);
            }
        };
        recyclerView.addOnScrollListener(mEndlessRecyclerOnScrollListener);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == 0 || newState == 1) {
                    Glide.with(BaseListFragment.this).resumeRequests();
                } else if (newState == 2) {
                    Glide.with(BaseListFragment.this).pauseRequests();
                }
            }
        });
        mAdapter = getAdapter();
        recyclerView.setAdapter(mAdapter);
    }


    @Override
    public void setEmptyViewVisibility(boolean isVisibility) {
        if (isVisibility && mAdapter.getItemCount() <= 0) {

            if (mEmptyView == null) {
                mEmptyView = mVsEmptyView.inflate();
                mEmptyView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mEmptyView.setVisibility(View.GONE);
                        setRefreshing(true);
                    }
                });
            }
            mEmptyView.setVisibility(View.VISIBLE);
        } else {
            if (mEmptyView != null) {
                mEmptyView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (isInitData) {
            loadingData(DELAYED);
        }
    }


    @Override
    public int getCreateViewLayoutRes() {
        return R.layout.fragment_list_view;
    }


    @Override
    public void setRefreshLayoutEnabled(boolean isEnabled) {

        refreshLayout.setEnabled(isEnabled);
    }

    @Override
    public void setRefreshing(boolean isRefreshing) {

        refreshLayout.setRefreshing(isRefreshing);
        if (isRefreshing) {
            refreshData();
        }
    }

    public void refreshDataSuccessful() {

        mEndlessRecyclerOnScrollListener.clearCacheData();
    }

    @Override
    public void onRefresh() {

        refreshData();
    }


    @Override
    public boolean isActive() {
        return isAdded();
    }

    public void setLayoutManager(RecyclerView.LayoutManager layout) {

        recyclerView.setLayoutManager(layout);
    }

    @NonNull
    public abstract BaseListAdapter getAdapter();

    public abstract void refreshData();

    public abstract void loadMoreData(int currentPage);

    public void onItemClick(View view, int position) {
        mPosition = position;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_DETAIL_CODE && resultCode == AppCompatActivity.RESULT_OK && data != null) {
            O o = data.getParcelableExtra(BasePresenter.RESULT_DETAIL_DATA_TAG);
            if (o != null && mPosition >= 0) {

                mAdapter.updateItemObject(o, mPosition);
            }
        } else if (requestCode == REQUEST_DETAIL_CODE && resultCode == BaseActivity.RESULT_OK_REFRESH) {

            setRefreshing(true);
        } else if (requestCode == REQUEST_DETAIL_CODE && resultCode == BaseActivity.RESULT_OK_DELETE) {

            mAdapter.removeItem(mPosition);
        }
    }
}
